import cv2, mediapipe as mp
mp_hands = mp.solutions.hands
mp_draw  = mp.solutions.drawing_utils

cap = cv2.VideoCapture("rtsp://admin:juhui2025@192.168.50.25:554/Streaming/Channels/102")
with mp_hands.Hands(max_num_hands=1,
                    min_detection_confidence=0.5,min_tracking_confidence=0.5) as hands:
    while cap.isOpened():
        ret, frame = cap.read()
        image = cv2.cvtColor(cv2.flip(frame, 1), cv2.COLOR_BGR2RGB)
        results = hands.process(image)
        if results.multi_hand_landmarks:
            for lm in results.multi_hand_landmarks:
                mp_draw.draw_landmarks(frame, lm,
                                       mp_hands.HAND_CONNECTIONS)
        cv2.imshow('Hands', frame)
        if cv2.waitKey(1) & 0xFF == 27: break
cap.release(); cv2.destroyAllWindows()


# 多线程，解决画点延迟问题，但是由于局域网内部延迟。
# import cv2
# import mediapipe as mp
# import threading
# from queue import Queue

# mp_hands = mp.solutions.hands
# mp_draw = mp.solutions.drawing_utils

# # 全局变量
# frame_queue = Queue(maxsize=1)
# result_queue = Queue(maxsize=1)
# stop_event = threading.Event()

# def capture_thread(cap):
#     while not stop_event.is_set() and cap.isOpened():
#         ret, frame = cap.read()
#         if not ret:
#             break
#         if frame_queue.empty():  # 只保留最新帧
#             frame_queue.put(frame)

# def process_thread(hands):
#     while not stop_event.is_set():
#         if not frame_queue.empty():
#             frame = frame_queue.get()
            
#             # 处理帧
#             image = cv2.cvtColor(cv2.flip(frame, 1), cv2.COLOR_BGR2RGB)
#             results = hands.process(image)
            
#             # 绘制结果
#             if results.multi_hand_landmarks:
#                 for lm in results.multi_hand_landmarks:
#                     mp_draw.draw_landmarks(frame, lm, mp_hands.HAND_CONNECTIONS)
            
#             if result_queue.empty():  # 只保留最新结果
#                 result_queue.put(frame)

# # 主函数
# def main():
#     cap = cv2.VideoCapture("rtsp://admin:juhui2025@192.168.50.25:554/Streaming/Channels/102")
#     hands = mp_hands.Hands(max_num_hands=1, min_detection_confidence=0.5,min_tracking_confidence=0.5)
    
#     # 启动线程
#     t1 = threading.Thread(target=capture_thread, args=(cap,))
#     t2 = threading.Thread(target=process_thread, args=(hands,))
#     t1.daemon = True
#     t2.daemon = True
#     t1.start()
#     t2.start()
    
#     try:
#         while True:
#             if not result_queue.empty():
#                 frame = result_queue.get()
#                 cv2.imshow('Hands', frame)
            
#             if cv2.waitKey(1) & 0xFF == 27:
#                 break
#     finally:
#         stop_event.set()
#         cap.release()
#         cv2.destroyAllWindows()
#         hands.close()

# if __name__ == "__main__":
#     main()